<?php

namespace App\Admin\Controllers;

use App\Admin\Traits\ModelFormRelations;
use App\Models\Car;
use App\Models\Cards;
use App\Models\CardSeries;
use App\Models\UserDrawLotsLog;
use Carbon\Carbon;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Support\MessageBag;

class CardsController extends Controller
{
    use ModelFormRelations;
    public function index($parent_id){
        $this->parent_id = $parent_id;
        return Admin::content(function (Content $content) {
            $card_series_name = CardSeries::where('id',$this->parent_id)->value('name');
            $content->header($card_series_name.'卡片管理');

            $content->body($this->grid());
        });
    }

    public function edit($parent_id,$id)
    {
        $this->parent_id = $parent_id;
        return Admin::content(function (Content $content) use ($id) {

            $content->header('卡片编辑');

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create($parent_id)
    {
        $this->parent_id = $parent_id;
        return Admin::content(function (Content $content) {

            $content->header('创建卡片');

            $content->body($this->form());
        });
    }

    protected function grid(){
        return Admin::grid(Cards::class, function (Grid $grid) {

            $grid->model()->where('card_series_id', $this->parent_id)->orderBy('sort','asc');

//            $grid->CarImgBig('图片')->image('',50,50);
            $grid->sort('排序');
            $grid->name('卡片名称');
            $grid->descr('卡片介绍');
            $grid->img('图片')->image('',50,50);
            $grid->rarity('稀有程度')->display(function($data){
                $rarity = "普通";
                switch ($data){
                    case 0:
                        $rarity = "普通";
                        break;
                    case 1:
                        $rarity = "珍贵";
                        break;
                    case 2:
                        $rarity = "稀有";
                        break;
                    case 3:
                        $rarity = "限定";
                        break;
                }
                return $rarity;
            });
            $grid->probability("中奖几率")->display(function($data){
                return $data."%";
            });
            $grid->startTime("开始时间");
            $grid->endTime("结束时间");

        });
    }
    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(Cards::class, function (Form $form) {
            $total = Cards::valid()->where('card_series_id',$this->parent_id)->sum('probability');
            $form->hidden('id', 'ID');
            $form->text('name','卡片名称')->rules('required');
            $form->hidden("sort",'排序')->default(0);
            $form->select("card_series_id",'卡片系列')->options(CardSeries::pluck('name','id'))->default($this->parent_id);

            $form->image('img','图片')->rules('required');
            $form->textarea('descr','卡片介绍')->rules('required');
            $form->select("rarity",'稀有程度')->options([0=>"普通",1=>"珍贵",2=>"稀有",3=>"限定"])->default(0);
            $form->rate("probability","中奖几率")->default(10)->help('当前该套卡片有效总概率为：'.$total.'%')
                ->rules('required|numeric|max:100',['max'=>'同套卡中总概率不能大于100%']);
            $form->datetimeRange("startTime","endTime","卡片可抽取时间")->rules('required');
            $form->hidden('alwaysGetStartTime')->default(Carbon::now()->toDateTimeString());
            $form->hidden('alwaysGetEndTime')->default(Carbon::now()->toDateTimeString());
    
            $form->saving(function ($form) {
                $current_probability = $form->model()->id
                    ? Cards::valid()->where('card_series_id',$form->model()->card_series_id)->where('id','<>',$form->id)->sum('probability')
                    : Cards::valid()->where('card_series_id',$form->card_series_id)->sum('probability');
                if($current_probability + $form->probability > 100){
                    $error = new MessageBag([
                        'title'   => '保存失败,所有卡片的抽取概率超过了100%',
                    ]);
                    return back()->with(compact('error'));
                }
                
            });
        });
    }
    
    public function destroy($pid,$id)
    {
        //删除前的判断
        //if(UserDrawLotsLog::where('card_id',$id)->exists()){
        //    return response()->json([
        //        'status'  => false,
        //        'message' => '删除失败，还有相关记录未删除',
        //    ]);
        //}
        if ($this->form()->destroy($id)) {
            UserDrawLotsLog::where('card_id',$id)->update(['card_id'=>0,'card_series_id'=>0]);
            return response()->json([
                'status'  => true,
                'message' => trans('admin.delete_succeeded').'已删除相关记录',
            ]);
        } else {
            return response()->json([
                'status'  => false,
                'message' => trans('admin.delete_failed'),
            ]);
        }
    }
}